'use strict';
const Controller = require('egg').Controller;

function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class StorehouseController extends Controller {

  async create() {
    const ctx = this.ctx;
    const params = ctx.request.body;
    console.log(params);
    const data = await ctx.model.Storehouse.create(params);
    ctx.body = {
      code: 0,
      data,
      message: '创建成功',
    };
  }

  async index() {
    const { ctx } = this;
    const { name, exist = -1, time, wime, pageSize = 10, current = 1 } = ctx.query;
    const limit = Number(pageSize);
    const offset = limit * ((current || 1) - 1);
    const query = {};
    if (name) { query.where = { ...query.where, name }; }
    if (exist !== -1) { query.where = { ...query.where, exist }; }
    if (time) { query.where = { ...query.where, time }; }
    if (wime) { query.where = { ...query.where, wime }; }
    const data = await ctx.model.Storehouse.findAll({ ...query, limit, offset });
    const result = data.map(x => {
      const info = x.dataValues;
      return {
        ...info,
        inventory: Number(info.accept) - Number(info.throw),
        throw: info.throw || 0,
      };
    });
    const totalData = await ctx.model.Storehouse.findAndCountAll();
    ctx.body = {
      code: 0,
      data: result,
      pageInfo: {
        total: totalData.count,
        current,
        pageSize: Number(pageSize),
      },
      message: 'success',
    };
  }

  async show() {
    const { ctx } = this;
    const detail = await ctx.model.Storehouse.findByPk(ctx.params.id, { raw: true });
    ctx.body = {
      code: 0,
      message: 'success',
      data: detail,
    };
  }

  async update() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const storehouse = await ctx.model.Storehouse.findByPk(id);
    if (!storehouse) {
      ctx.body = {
        code: 1,
        data: [],
        message: '不存在的库存',
      };
      return;
    }
    const params = ctx.request.body;
    console.log('--', params);
    const data = await storehouse.update(params);
    ctx.body = {
      code: 0,
      data,
      message: '更新成功',
    };
  }

  async destroy() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const storehouse = await ctx.model.Storehouse.findByPk(id);
    if (!storehouse) {
      ctx.body = {
        code: 1,
        data: [],
        message: '不存在的产品',
      };
      return;
    }

    await storehouse.destroy();
    ctx.body = {
      code: 0,
      message: '删除成功',
    };
  }
}

module.exports = StorehouseController;
